package com.lucian.ge.user.controller;

import com.alibaba.fastjson.JSON;
import com.lucian.ge.user.mapper.UserMapper;
import com.lucian.ge.comman.model.ResultMap;
import io.swagger.annotations.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import org.springframework.http.HttpHeaders;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by Lucicol on 2019/5/10.
 */
@Api(value = "SmsCodeController", description = "短信验证码接口")
@RestController
@RequestMapping("/smsSignup")
public class SmsCodeController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    private final UserMapper userMapper;
    private final ResultMap resultMap;
    @Value("${com.smsURL}")
    private String smsURL;
    @Value("${com.apikey}")
    private String apikey;

    @Autowired
    public SmsCodeController(UserMapper userMapper, ResultMap resultMap) {
        this.userMapper = userMapper;
        this.resultMap = resultMap;
    }

    @ApiOperation(value="发送短信", notes="")
    @PostMapping("/send")
    @ResponseBody
    public ResultMap sendSms(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) SMSUser smsUser, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String remoteAddr = httpServletRequest.getRemoteAddr();

        //        图形验证码过期
        if (redisTemplate.opsForValue().get(smsUser.getUsername()+"gv") == null) {
            return resultMap.fail().code(401).message("图形验证码过期请刷新");
        }

//        图形验证码校验
        if (!smsUser.getGvcode().equals(redisTemplate.opsForValue().get(smsUser.getUsername()+"gv"))) {
            return resultMap.fail().code(401).message("图形验证码错误");
        }

//        手机号限制
        if (redisTemplate.opsForValue().get(smsUser.getUsername()+"exist") != null) {
            return resultMap.fail().code(401).message("每个手机号,24小时内只能申请1次验证,请明天再来申请");
        }

//        ip限制
        if (redisTemplate.opsForValue().get(remoteAddr+"exist") != null) {
            return resultMap.fail().code(401).message("每个ip,12小时内只能申请1次验证,请明天再来申请");
        }

//        sms验证码
        String code = String.valueOf((int)((Math.random()*9+1)*1000));
//        限制时间
        redisTemplate.opsForValue().set(smsUser.getUsername()+"sms", code, 60 * 30, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(smsUser.getUsername()+"exist", "exist", 60 * 60 * 24, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(remoteAddr+"exist", "exist", 60 * 60 * 12, TimeUnit.SECONDS);

        LinkedMultiValueMap params = new LinkedMultiValueMap();
        params.add("apikey", apikey);
//        params.add("text", "【07ge灵气分享】验证码" + code + "(07ge手机验证码，请完成验证)，30分钟有效，如非本人操作，请忽略本短信");
        params.add("text", "【07ge灵气分享】" + code + "(07ge手机验证码，请完成验证)，如非本人操作，请忽略本短信" );
        params.add("mobile", smsUser.getUsername());

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        headers.add("Accept", "application/json");

        HttpEntity entity = new HttpEntity(params, headers);

        RestTemplate restTemplate = new RestTemplate();

        String result = restTemplate.postForObject(smsURL , entity , String.class);

        // 抓错误

        // 调试
        return resultMap.success().code(200).message("验证码发送成功,请于手机短信中查收").res(result);

//        return resultMap.success().code(200).message("验证码发送成功,请于手机短信中查收");
    }
}

@ApiModel
class SMSUser {
    @ApiModelProperty(value = "手机号码")
    private String username;

    @ApiModelProperty(value = "图形验证码")
    private String gvcode;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getGvcode() {
        return gvcode;
    }

    public void setGvcode(String gvcode) {
        this.gvcode = gvcode;
    }
}